package io.renren.modules.medical.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.PageList;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.DoctorInfoUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.medical.dao.PatientInfoDao;
import io.renren.modules.medical.entity.*;
import io.renren.modules.medical.service.*;
import io.renren.modules.medical.vo.medicalVo.PatientTreeVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2023-03-23 22:36
 */
@RequiredArgsConstructor
@Service("PatientInfoService")
public class PatientInfoServiceImpl extends ServiceImpl<PatientInfoDao, PatientInfoEntity> implements PatientInfoService {

    private final DoctorInfoService doctorInfoService;

    private final IllSubService illSubService;

    private final WebSocketInterService webSocketInterService;

    private final PatientDoctorRelativeService patientDoctorRelativeService;



    /**
     *
     * 通过发送token信息返回当前的用户id
     * 通过拿到的用户id查询得到医生信息
     * 通过医生id信息返回：病人姓名，病情描述，病人id
     * 最后返回分页数据
     * 将分页对象中的total封装成patientListVo返回给前端
     */
    @Override
    public PageUtils queryPageByUserId(Map<String, Object> params) {

        // 获取docId
        Long docId = DoctorInfoUtils.getDoctorInfo(doctorInfoService).getId();

        // 根据docId获取对应的patientId集合
        List<Long> patientIdList = getPatientIdList(docId);
        String key = (String)params.get("key");
        LambdaQueryWrapper<PatientInfoEntity> queryWrapper = new LambdaQueryWrapper<>();

        // 执行查询
        if (patientIdList.size() > 0){
            queryWrapper.in(PatientInfoEntity::getId, patientIdList);
        }else {
            return new PageUtils(new ArrayList<PatientInfoEntity>(), 0, 0, 0);
        }

        // 添加构造参数
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and(
                    obj -> obj.eq(BaseEntity::getId, key).or().like(PatientInfoEntity::getName, key)
            );
        }
        IPage<PatientInfoEntity> page = this.page(new Query<PatientInfoEntity>().getPage(params), queryWrapper);

        // 获取到分页对象中的PatientInfoEntity，重新封装
        List<PatientInfoEntity> infoEntities = page.getRecords();
        List<PatientInfoEntity> patientList = infoEntities.stream().map(item -> {
            // 得到为查看的数量
            Integer count = webSocketInterService.getNoneVisitCount(item.getId(), docId);
            item.getParam().put("noneVisitCount", count);
            return item;
        }).collect(Collectors.toList());

        // 将patientListVos封装进page中
        page.setRecords(patientList);
        return new PageUtils(page);
    }

    private List<Long> getPatientIdList(Long docId) {
        LambdaQueryWrapper<PatientDoctorRelativeEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(docId != null, PatientDoctorRelativeEntity::getDoctorId, docId);
        List<PatientDoctorRelativeEntity> list = patientDoctorRelativeService.list(lambdaQueryWrapper);
        List<Long> patientIdList = list.stream().map(PatientDoctorRelativeEntity::getPatientId).collect(Collectors.toList());
        return patientIdList;
    }

    @Override
    public String getNameById(Long id) {
        PatientInfoEntity infoEntity = null;
        if (id != null) {
            infoEntity = this.getById(id);
        }

        return infoEntity != null ? infoEntity.getName() : null;
    }


    @Override
    public List<Long> getIdsByName(String patientName) {
        LambdaQueryWrapper<PatientInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(patientName), PatientInfoEntity::getName, patientName);
        List<PatientInfoEntity> list = this.list(queryWrapper);
        return list.stream().map(PatientInfoEntity::getId).collect(Collectors.toList());
    }

    @Override
    public List<PatientTreeVo> patientTree() {
        // 1、先获取到一级的illSub
        List<IllSubEntity> oneLevelIll = illSubService.getChildren(0L);
        // 2、封装到PatientTreeVo中
        List<PatientTreeVo> oneLevelTree = oneLevelIll.stream().map(item1 -> {
            PatientTreeVo patientTreeVo1 = new PatientTreeVo();
            patientTreeVo1.setLabel(item1.getTitle());
            patientTreeVo1.setValue(item1.getId());
            // 3、封装二级树
            List<IllSubEntity> twoLevelIll = illSubService.getChildren(item1.getId());
            IllSubEntity subEntity = illSubService.getById(item1.getId());
            twoLevelIll.add(subEntity);
            // 如果二级分类为空就直接返回

            List<PatientTreeVo> tree2 = twoLevelIll.stream().map(item2 -> {
                PatientTreeVo patientTreeVo2 = new PatientTreeVo();
                patientTreeVo2.setLabel(item2.getTitle());
                patientTreeVo2.setValue(item2.getId());
                // 封装第三层
                LambdaQueryWrapper<PatientDoctorRelativeEntity> relativeWrapper = new LambdaQueryWrapper<>();
                relativeWrapper.eq(PatientDoctorRelativeEntity::getSubId, item2.getId());
                List<PatientDoctorRelativeEntity> relativeEntities = patientDoctorRelativeService.list(relativeWrapper);
                // 如果三级分类为空就直接返回
                if (relativeEntities == null || relativeEntities.size() <= 0) {
                    patientTreeVo2.setChildren(null);
                    return patientTreeVo2;
                }
                // 反之就查询到对应的所有病人
                List<Long> patientIds = relativeEntities.stream().map(PatientDoctorRelativeEntity::getPatientId).collect(Collectors.toList());
                LambdaQueryWrapper<PatientInfoEntity> patientWrapper = new LambdaQueryWrapper<>();
                patientWrapper.in(PatientInfoEntity::getId, patientIds);
                List<PatientInfoEntity> patientInfoEntityList = this.list(patientWrapper);
                List<PatientTreeVo> tree3 = patientInfoEntityList.stream().map(item3 -> {
                    PatientTreeVo patientTreeVo3 = new PatientTreeVo();
                    patientTreeVo3.setLabel("姓名：" + item3.getName() + " 电话：" + item3.getPhone());
                    patientTreeVo3.setValue(item3.getId());
                    patientTreeVo3.setChildren(null);
                    return patientTreeVo3;
                }).collect(Collectors.toList());

                // 封装第二层的子集
                patientTreeVo2.setChildren(tree3);
                return patientTreeVo2;
            }).collect(Collectors.toList());

            // 封装第一层的子集
            patientTreeVo1.setChildren(tree2);
            return patientTreeVo1;

        }).collect(Collectors.toList());
        return oneLevelTree;
    }

    @Override
    public List<PatientInfoEntity> getPatients(Long subId) {
        DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
        LambdaQueryWrapper<PatientDoctorRelativeEntity> patientDoctorRelativeWrapper = new LambdaQueryWrapper<>();
        patientDoctorRelativeWrapper.eq(PatientDoctorRelativeEntity::getSubId, subId);
        patientDoctorRelativeWrapper.eq(PatientDoctorRelativeEntity::getDoctorId, doctorInfo.getId());
        List<PatientDoctorRelativeEntity> list = patientDoctorRelativeService.list(patientDoctorRelativeWrapper);
        if (list == null || list.size() <= 0){
            return new ArrayList<>();
        }
        List<Long> patientIds = list.stream().map(PatientDoctorRelativeEntity::getPatientId).collect(Collectors.toList());
        LambdaQueryWrapper<PatientInfoEntity> patientInfoWrapper = new LambdaQueryWrapper<>();
        patientInfoWrapper.in(PatientInfoEntity::getId, patientIds);
        return this.list(patientInfoWrapper);
    }

}



